package com.tea.servlet;

import com.tea.entity.User;
import com.tea.service.UserService;
import com.tea.service.impl.UserServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import java.util.UUID;
import java.io.File;
import javax.servlet.http.Part;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/user/profile")
@MultipartConfig(maxFileSize = 10485760) // 限制文件大小为10MB
public class UserProfileServlet extends HttpServlet {
    private final UserService userService = new UserServiceImpl();

    // 获取文件扩展名
    private String getFileExtension(String fileName) {
        if (fileName == null || fileName.lastIndexOf('.') == -1) {
            return ".jpg"; // 默认扩展名
        }
        return fileName.substring(fileName.lastIndexOf('.'));
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        User currentUser = (User) session.getAttribute("user");
        if (currentUser == null) {
            resp.sendRedirect("/login.jsp");
            return;
        }
        req.setAttribute("user", currentUser);
        req.getRequestDispatcher("/profile-edit.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        HttpSession session = req.getSession();
        User currentUser = (User) session.getAttribute("user");

        if (currentUser == null) {
            resp.sendRedirect("/login.jsp");
            return;
        }

        // 获取表单提交的用户信息
        String email = req.getParameter("email");
        String phone = req.getParameter("phone");
        String avatarPath = currentUser.getAvatar(); // 默认使用当前头像

        // 处理文件上传
        try {
            Part filePart = req.getPart("avatar");
            if (filePart != null && filePart.getSize() > 0) {
                // 获取上传目录路径
                String uploadDir = getServletContext().getRealPath("/uploads/avatars");
                File uploadDirFile = new File(uploadDir);
                if (!uploadDirFile.exists()) {
                    uploadDirFile.mkdirs(); // 创建目录（包括父目录）
                }

                // 生成唯一文件名
                String fileName = UUID.randomUUID().toString() + getFileExtension(filePart.getSubmittedFileName());
                String filePath = uploadDir + File.separator + fileName;

                // 保存文件到服务器
                filePart.write(filePath);
                avatarPath = "/uploads/avatars/" + fileName; // 存储相对路径
            }
        } catch (Exception e) {
            req.setAttribute("errorMsg", "文件上传失败：" + e.getMessage());
            req.getRequestDispatcher("/profile-edit.jsp").forward(req, resp);
            return;
        }

        // 更新用户信息
        currentUser.setEmail(email);
        currentUser.setPhone(phone);
        currentUser.setAvatar(avatarPath);

        try {
            boolean updateSuccess = userService.updateUserInfo(currentUser);
            if (updateSuccess) {
                session.setAttribute("user", currentUser); // 更新session中的用户信息
                resp.sendRedirect("/profile-success.jsp");
            } else {
                req.setAttribute("errorMsg", "更新个人信息失败，请重试");
                req.getRequestDispatcher("/profile-edit.jsp").forward(req, resp);
            }
        } catch (Exception e) {
            req.setAttribute("errorMsg", "更新失败：" + e.getMessage());
            req.getRequestDispatcher("/profile-edit.jsp").forward(req, resp);
        }
    }
}